<?php
declare (strict_types=1);

namespace app\admin\service\system;

use app\admin\logic\system\Config as SystemConfig;
use app\common\exception\LogicException;
use app\common\service\BaseService;
use app\user\tools\tencent\Face;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\page\PageForm;
use think\Request;
use think\Response;
use Throwable;

/**
 * 配置接口
 */
class Config extends BaseService
{
    /**
     * 通用配置保存方法
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-25
     *
     * @param Request $request [description]
     * @return Response [type]                                  [description]
     */
    public function save(Request $request): Response
    {
        $data = $request->post();
        $key  = $data['__key'];
        unset($data['__key']);
        SystemConfig::set($key, $data);

        return $this->parseToData([], 1, '保存成功');
    }

    /**
     * 登录配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-25
     *
     * @return Response [type]                         [description]
     */
    public function login(): Response
    {
        // 字段定义
        $fields = [
            'unique' => FormItem::make('SlideSwitch')->title('唯一登录')->activeValue()->inactiveValue(0),
            'type'   => FormItem::make('checkbox')->options([
                ['title' => '一键登录', 'value' => 'phone'],
                ['title' => '短信验证码', 'value' => 'verify'],
                ['title' => '账号密码', 'value' => 'user'],
                ['title' => '设备登录', 'value' => 'device'],
            ])->title('登录方式'),
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'system.login';
        $config          = SystemConfig::get($key, [], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 一键登录配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-17
     */
    public function oneclick(): Response
    {
        $help = '请前往<a href="https://dun.163.com/">网易易盾</a>获取配置，号码认证栏-';
        // 字段定义
        $fields = [
            'secretId'   => FormItem::make()->title('secretId')->required()->help($help . '已开通业务-查看产品密钥'),
            'secretKey'  => FormItem::make()->title('secretKey')->required()->help($help . '已开通业务-查看产品密钥'),
            'businessId' => FormItem::make()->title('businessId')->required()->help($help . '对应业务ID'),
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'system.login.oneclick';
        $config          = SystemConfig::get($key, [], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 小程序配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-17
     */
    public function miniapp(): Response
    {
        // 字段定义
        $fields = [
            'appid'  => FormItem::make()->title('appid')->required(),
            'secret' => FormItem::make()->title('secret')->required()
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'system.login.miniapp';
        $config          = SystemConfig::get($key, [], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 公众号配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-17
     */
    public function official(): Response
    {
        // 字段定义
        $fields = [
            'appid'  => FormItem::make()->title('appid')->required(),
            'secret' => FormItem::make()->title('secret')->required()
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'system.config.official';
        $config          = SystemConfig::get($key, [], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 系统配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-19
     *
     * @return Response [type]                         [description]
     */
    public function category(): Response
    {
        $fields        = [
            'use_public' => FormItem::make('SlideSwitch')->title('使用全局分类')->activeValue()->inactiveValue(0)->help('开启后所有模块的分类将使用课程分类，其他分类配置将失效'),
        ];
        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'system.category';
        $config          = SystemConfig::get($key, ['use_public' => 0], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * 获取配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-22
     *
     * @param $__key
     * @return Response [type]                         [description]
     */
    public function getConfig($__key): Response
    {
        $data = SystemConfig::get($__key, [], request()->mhm_id);

        return $this->parseToData($data, 1);
    }

    /**
     * 分享配置
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2021-01-19
     *
     * @return Response [type]                      [description]
     */
    public function share(): Response
    {
        // 字段定义
        $fields = [
            'course' => FormItem::make('SlideSwitch')->title('课程分享强制登录')->activeValue()->inactiveValue(0),
            // 'topic'     => FormItem::make('SlideSwitch')->title('资讯分享强制登录')->activeValue(1)->inactiveValue(0),
        ];

        $form          = new PageForm();
        $form->pageKey = $fields;
        $form->withSystemConfig();
        $key             = 'share.config';
        $config          = SystemConfig::get($key, [], request()->mhm_id);
        $config['__key'] = $key;
        $form->datas     = $config;

        return $form->send();
    }

    /**
     * face
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/12/2
     *
     * @return Response
     */
    public function face(): Response
    {
        if (\think\facade\Request::isPost()) {
            $data = \think\facade\Request::post();
            if (!isset($data['secret_id']) || !$data['secret_id']) {
                throw new LogicException('云API密钥-SecretId 不能为空');
            }

            if (!isset($data['secret_key']) || !$data['secret_key']) {
                throw new LogicException('云API密钥-SecretKey 不能为空');
            }

            $groupId         = $data['group_id'] ?? 'eduline-v5';
            $groupName       = $data['group_name'] ?? 'eduline-v5人脸库';
            $tencentFaceTool = new Face($data['secret_id'], $data['secret_key'], $groupId);
            try {
                $tencentFaceTool->getGroupInfo(['GroupId' => $groupId]);
            } catch (Throwable $exception) {
                // 创建默认的人脸库
                $tencentFaceTool->createGroup([
                    "GroupName" => $groupName,
                    "GroupId"   => $groupId
                ]);
            }

            $key = $data['__key'];
            unset($data['__key']);
            $data['group_name'] = $groupName;
            $data['group_id']   = $groupId;
            SystemConfig::set($key, $data);

            return $this->parseToData([], 1, '保存成功');
        }
        // 字段定义
        $fields = [
            'scene'           => FormItem::make('checkbox')->title('启用场景')->options([
                ['title' => '学习课程', 'value' => 'course'],
                ['title' => '考试', 'value' => 'exam']
            ])->help('启用场景后，会在触发场景时要求人脸认证通过后才能继续操作'),
            'verify_number'   => FormItem::make('inputNumber')->title('随机验证次数')->min(0)->max(5)->help('1. 随机验证最大次数<br />2. 可设置0-5次'),
            'verify_timespan' => FormItem::make('inputNumber')->title('随机验证时间间隔')->min(1)->help('1. 随机验证时间间隔<br />2. 单位：分钟'),
            'secret_id'       => FormItem::make()->title('云API密钥-SecretId')->help('推荐创建子账号,赋予子账号人脸识别权限')->required(),
            'secret_key'      => FormItem::make()->title('云API密钥-SecretKey')->help('推荐创建子账号,赋予子账号人脸识别权限')->required(),
            'group_name'      => FormItem::make()->title('默认人员库名称')->help('默认为：eduline-v5人脸库'),
            'group_id'        => FormItem::make()->title('默认人员库ID')->help('默认为：eduline-v5'),
        ];

        $form              = new PageForm();
        $form->pageKey     = $fields;
        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/admin/system/config/face';
        $key               = 'face.config';
        $config            = SystemConfig::get($key, ['group_name' => 'eduline-v5人脸库', 'group_id' => 'eduline-v5'], request()->mhm_id);
        $config['__key']   = $key;
        $form->datas       = $config;

        return $form->send();
    }
}
